<?php

namespace app\admin\controller;

use think\Controller;
use think\Db;
use think\Request;
use app\admin\model\Category as CategoryModel;
class Category extends Controller
{
    protected $db;
    public function _initialize ( Request $request = null )
    {
        $this->db = new CategoryModel();
    }
    /**
     * 栏目显示
     *
     * @return \think\Response
     */
    public function index(CategoryModel $CategoryModel)
    {
        $category = $this->db->getAllCate();
        $this->assign('category',$category);
        return view();
    }

    /**
     * 栏目添加
     *
     * @return \think\Response
     */
    public function post()
    {
        $cid=input('param.cid');
        $model= $cid ? CategoryModel::find($cid) : new CategoryModel();

        if (request()->isPost()){
            $res=$model->validate(true)->save(input('post.'));
            if(false === $res){
                // 验证失败 输出错误信息
                $this->error($model->getError());
            }else{
                $this->success('操作成功','index');
            }
        }
        if ( !$cid ) {
            //说明是添加
            $model = [ 'cate_name' => '' , 'pid' =>0 , 'cate_sort' => 0 ];
        }
        if($cid){
            //编辑
            $oldData = $this->db->getCateData($cid);
        }else{
            //添加
            $oldData = $this->db->getAllCate();
        }
        return view('',compact('model','oldData'));
    }


    public function del(){


        $cid = input( 'get.cid' );
        //删除之前，当前栏目如果有子集栏目，则不允许删除
        if(db('category')->where('pid',$cid)->select()){
            $this->error( '请先删除子集栏目' );exit;
        }
        //执行删除
        if ( CategoryModel::destroy( $cid ) ) {
            $this->success( '操作成功' , 'index' );
            exit;
        } else {
            $this->error( '操作失败' );exit;
        }
    }
}
